import { appendFileSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';

// 清空 __all__.js 文件
writeFileSync('./src/device/__all__.js', '', { encoding: 'utf-8' });
// 定义忽略的文件名列表
// 因为一些特殊的文件结构不适用，当前是010100011_瘦西湖开发板
const ignoreFiles = ['xx.json'];
// 读取 JSON 文件
// const inputFiles = readdirSync('./input', { encoding: 'utf-8' }).filter((file) => file.endsWith('.json'));
// 读取 JSON 文件
const inputFiles = readdirSync('./input', { encoding: 'utf-8' }).filter((file) => {
    return file.endsWith('.json') && !ignoreFiles.includes(file);
});
// 遍历 JSON 文件
inputFiles.forEach((file) => {
    // 读取文件内容
    const data = JSON.parse(readFileSync(`./input/${file}`, { encoding: 'utf-8' }).toString());

    // 获取类别信息
    const categoryAlias = data.categoryAlias;

    // 生成内容
    const content = generateContent(data);

    // 写入文件
    writeFileSync(`./src/device/${categoryAlias}.js`, content, { encoding: 'utf-8' });

    // 写入 __all__.js 文件
    appendFileSync('./src/device/__all__.js', `export { default as ${categoryAlias} } from './${categoryAlias}';\n`, {
        encoding: 'utf-8',
    });

    console.log(`Generated ${categoryAlias}`);
});

// 生成内容
function generateContent(data) {
    const { categoryAlias, categoryCode, categoryName, methods } = data;

    const keys = Object.keys(methods);

    // 添加类的头部
    let content = `/**
 * 自动生成！请勿修改！
 */
import { command } from '../core/command';

class ${categoryAlias} {
    constructor(opt = {}) {
        const { device, to, ...opts } = opt;

        this.device = device || {};
        this.opts = opts || {};
        this._to = to;
    }

    get categoryCode() {
        return '${categoryCode}';
    }

    get categoryName() {
        return '${convertUnicode(categoryName)}';
    }
`;

    // 添加类的方法
    keys.forEach((key) => {
        const { method, methodId, timeout } = methods[key];

        if (timeout) {
            content += `
    ${method}(params) {
        return command({
            method: '${method}',
            methodId: '${methodId}',
            params,
            to: this.to?.[this.i] || this.to,
            timeout: ${timeout},
        });
    }
`;
        } else {
            content += `
    ${method}(params) {
        return command({
            method: '${method}',
            methodId: '${methodId}',
            params,
            to: this.to?.[this.i] || this.to,
        });
    }
`;
        }
    });

    // 添加类的尾部
    content += `}

export default ${categoryAlias};
`;

    return content;
}

// 转换编码
function convertUnicode(string) {
    let result = '';

    for (let i = 0; i < string.length; i++) {
        result += '\\u' + string.charCodeAt(i).toString(16).padStart(4, '0');
    }

    return result;
}
